﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text;
using UnityEditor;
using Model;

namespace MyEditor
{
    /// <summary>
    /// AB包工具
    /// </summary>
    public class AssetBundleTools : ScriptableObject
    {

        /// <summary>
        /// 设置assetbundle标签
        /// </summary>
        /// <param name="isRemove"></param>
        public static void SetAllLabels()
        {
            AssetDatabase.RemoveUnusedAssetBundleNames();

            // 需要打包的资源目录
            DirectoryInfo resDir = new DirectoryInfo(PathHelper.resPath);

            // 资源目录不存在
            if (!resDir.Exists)
                return;

            // 获取资源目录下的所有文件、文件夹
            DirectoryInfo[] sceneDir = resDir.GetDirectories();
            foreach (var item in sceneDir)
            {
                var sceneName = item.Name;

                // 每一个场景文件夹
                SetAllLabels(item, sceneName);
            }

        }

        /// <summary>
        /// 移除所有的标签
        /// </summary>
        public static void RemoveAllLables()
        {
            foreach (var item in AssetDatabase.GetAllAssetBundleNames())
            {
                AssetDatabase.RemoveAssetBundleName(item, true);
            }
        }

        /// <summary>
        /// windows打包
        /// </summary>
        public static void BuildWindows()
        {
            Build(PathHelper.windowTargetPath, BuildTarget.StandaloneWindows);
        }

        public static void BuildWindowsToServer()
        {
            string targetPath = PathHelper.ResServerPath + "Windows";
            Build(targetPath, BuildTarget.StandaloneWindows);
            BuildHelper.GenerateVersionInfo(targetPath);
        }

        public static void BuildAndroid()
        {
            Build(PathHelper.androidTargetPath, BuildTarget.Android);
        }

        public static void CreateVersion()
        {
            BuildHelper.GenerateVersionInfo(PathHelper.windowTargetPath);
            AssetDatabase.Refresh();
        }

        /// <summary>
        /// 删除所有打包
        /// </summary>
        public static void DeleteAll()
        {
            try
            {
                File.Delete(PathHelper.windowTargetPath + ".meta");
                File.Delete(PathHelper.androidTargetPath + ".meta");
                Directory.Delete(PathHelper.windowTargetPath, true);
                Directory.Delete(PathHelper.androidTargetPath, true);
            }
            catch (System.Exception e)
            {
                Debug.Log(e.Message);
            }

            AssetDatabase.Refresh();
        }

        public static void OpenServerResDir()
        {
            System.Diagnostics.Process.Start(System.Environment.CurrentDirectory +"/"+ PathHelper.ResServerPath);
        }
        public static void OpenPersistentDataDir()
        {
            System.Diagnostics.Process.Start(Application.persistentDataPath);
        }

        /// <summary>
        /// 打开资源服务器
        /// </summary>
        public static void OpenFileServer()
        {
            string currentDir = System.Environment.CurrentDirectory;
            string path = Path.Combine(currentDir, @"..\FileServer\");
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = "FileServer.exe";
            process.StartInfo.WorkingDirectory = path;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
        }

        /// <summary>
        /// 打包
        /// </summary>
        /// <param name="targetPath"></param>
        /// <param name="buildTarget"></param>
        private static void Build(string targetPath, BuildTarget buildTarget)
        {
            if (!Directory.Exists(targetPath))
            {
                Directory.CreateDirectory(targetPath);
            }

            BuildPipeline.BuildAssetBundles(targetPath, BuildAssetBundleOptions.None, buildTarget);
            AssetDatabase.Refresh();
        }

        /// <summary>
        /// 遍历指定文件夹中的文件
        /// </summary>
        /// <param name="fileSystemInfo"></param>
        /// <param name="sceneName"></param>
        private static void SetAllLabels(FileSystemInfo fileSystemInfo, string sceneName)
        {
            // 目录
            var dir = fileSystemInfo as DirectoryInfo;

            // 拿到当前目录下的文件
            var fsis = dir.GetFileSystemInfos();

            foreach (var item in fsis)
            {
                // 如果是文件，就直接设置assetbundle标签。
                var fileInfo = item as FileInfo;
                if (fileInfo != null)
                {
                    SetLabel(fileInfo, sceneName);
                }
                else
                {
                    SetAllLabels(item, sceneName);
                }
            }
        }

        /// <summary>
        /// 设置文件的assetbundle标签
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <param name="sceneName"></param>
        private static void SetLabel(FileInfo fileInfo, string sceneName)
        {
            

            // 把window \ 路径 转换为unity路径 /
            var path = fileInfo.FullName.Replace(@"\", "/");
            if (fileInfo.Extension == ".meta")
                return;

            // 截取出场景后面的路径
            var startIndex = path.IndexOf(sceneName) + sceneName.Length + 1;

            path = path.Substring(startIndex);

            var name = sceneName;

            // 如果包含 / 表示不在 场景目录下
            if (path.Contains("/"))
            {
                var twoDir = path.Split('/')[0];
                name = sceneName + "/" + twoDir;
            }

            // 设置assetbundle标签
            AssetImporter assetImporter = AssetImporter.GetAtPath("Assets/Bundles/" + sceneName + "/" + path);
            assetImporter.assetBundleName = name;
            if (fileInfo.Extension != ".unity")
            {
                assetImporter.assetBundleVariant = "assetbundle";
            }
            else
            {
                assetImporter.assetBundleVariant = "unity3d";
            }
        }
    }
}
